package com.ruoyi.analyse.service;


import com.ruoyi.analyse.model.SafetyDto;
import com.ruoyi.analyse.model.FileDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.PreDestroy;
import java.io.File;
import java.util.List;

@Slf4j
public class SafetyTemplate extends Thread {
    private CollectFileReader fileReader;
    private CollectFileFilter fileFilter;
    private CollectParser parse;
    private SafetyDto mapper;

    public SafetyTemplate(final CollectFileReader fileReader, final CollectFileFilter fileFilter, CollectParser parse, final SafetyDto mapper, String threadName) {
        this.fileReader = fileReader;
        this.fileFilter = fileFilter;
        this.parse = parse;
        this.mapper = mapper;
        this.setName(threadName);
    }

    @Override
    public void run() {
        log.info("start");
        try {
            while (!Thread.interrupted()) {
                Thread.sleep(mapper.getWaitTime());
                long start = System.currentTimeMillis();
                log.info("start_collect");
                collect();
                long cost = System.currentTimeMillis() - start;
                log.info("end_collect[{}]", cost);
            }
        } catch (InterruptedException ie) {
            log.warn("interrupted", ie);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            log.error("exception", e);
        }
        log.info("end");
    }

    @PreDestroy
    public void preDestroy() {
        log.info("predestroy");
    }


    public void collect() {
        try {
            List<FileDto> files = fileReader.getFiles();
            if (CollectionUtils.isEmpty(files)) {
                log.warn("no_file");
                return;
            }
            files = fileFilter.filter(files);
            if (CollectionUtils.isEmpty(files)) {
                log.warn("file_filter");
                return;
            }

            parse.parse(files);

            files.forEach(f -> delete(f.getPath()));


        } catch (Exception e) {
            log.warn("", e);
        }
    }

    private boolean delete(String filePath) {
        for (int i = 0; i < 2; i++) {
            boolean delete = new File(filePath).delete();
            if (delete) {
                return true;
            }
            System.gc();
            log.warn("delete_count:[{}]", i);
        }
        return false;
    }
}
